package com.wgz.mcp.service;

import com.alibaba.cloud.ai.dashscope.embedding.DashScopeEmbeddingModel;
import com.wgz.mcp.excutor.QdRantExcutor;
import com.wgz.mcp.mapper.DepotHeadMapper;
import io.metaloom.qdrant.client.grpc.QDrantGRPCClient;
import io.metaloom.qdrant.client.grpc.proto.JsonWithInt;
import jakarta.annotation.Resource;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class KnowledgeBaseService {

    @Value("${spring.vectorstore.qdrant.collection-name}")
    private String qdrantCollectionName;

    @Value("${spring.vectorstore.qdrant.temperature}")
    private String temperature;

    @Resource
    private DashScopeEmbeddingModel dashScopeEmbeddingModel;

    @Resource
    private QDrantGRPCClient qDrantGRPCClient;

    @Resource
    private DepotHeadMapper depotHeadMapper;

    @Tool(description = "从知识库查询erp系统内的业务数据信息")
    public String queryFromQdrant(
            @ToolParam(required = true, description = "用户的问题，用于到向量数据库进行匹配查询") String question
            , @ToolParam(required = true, description = "tenantId，用于在向量数据库中查操作时进行租户维度的资源隔离") Long tenantId
    ){
        return QdRantExcutor.queryFromQdrant(tenantId.toString(),dashScopeEmbeddingModel,question,qdrantCollectionName,temperature,qDrantGRPCClient);
    }


    @Tool(description = "更新单据的审核状态")
    public String updateOrderStatusFromQdrant(
            @ToolParam(required = true, description = "需要更新状态的单据id,格式为2到5位大写字母开头11位数字结尾") String orderId
            ,@ToolParam(required = true, description = "用户输入的期望更新后的单据状态,只有3个状态：已审核、未审核、已完成") String orderStatus
            , @ToolParam(required = true, description = "tenantId，用于在向量数据库中查操作时进行租户维度的资源隔离") Long tenantId
    ){
        String vectorId = depotHeadMapper.selectVectorIdByOrderId(orderId);
        Map<String, JsonWithInt.Value> pointById = QdRantExcutor.getPointById(vectorId, qDrantGRPCClient);
        String text_segment = pointById.get("text_segment").getStringValue();
        String tenantIdFromQdrant = pointById.get("tenant_id").getStringValue();
        if (tenantId.toString().equals(tenantIdFromQdrant)){
            String status = depotHeadMapper.selectStatusByOrderId(orderId, tenantId);
            //修改需要修改的向量库内容，准备写入qdrant
            switch (status){
                case "0":
                    if (StringUtils.pathEquals(orderStatus, "已审核")) {
                        text_segment = text_segment.replaceAll("未审核", orderStatus);
                    }else {
                        return "当前单据不能修改为" + orderStatus;
                    }
                    break;
                case "1":
                    if (StringUtils.pathEquals(orderStatus, "未审核")) {
                        text_segment = text_segment.replaceAll("已审核",orderStatus);
                    } else {
                        return "当前单据不能修改为" + orderStatus;
                    }
                    break;
                case "2":
                    return "该状态的单据无法直接更改，需要先处理下游单据";
            }
            //将orderStatus改为状态码，准备写入db
            switch (orderStatus){
                case "未审核":
                    orderStatus = "0";
                    break;
                case "已审核":
                    orderStatus = "1";
                    break;
                case "已完成":
                    return "生成下游单据时自动更改，不需要手动修改状态";
            }
            depotHeadMapper.updateOrderStatus(orderId,orderStatus);
            QdRantExcutor.writeToQdrant(qDrantGRPCClient,dashScopeEmbeddingModel,text_segment,tenantIdFromQdrant,vectorId);
            return "更新单据状态成功";
        }else {
            throw new RuntimeException("非当前租户单据，无法操作");
        }
    }

}
